<template>
  <div class="app-main-container" style="padding-top: 20px;">
    <div>
      <div class="doumee-filter">
        <el-form inline label-suffix="：" @submit.native.prevent>
          <el-form-item :label="$t('message.sbzt')">
            <el-select v-model="filters.state" :placeholder="$t('message.qxz') + $t('message.sbzt')" clearable>
              <el-option
                v-for="item in stateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('message.sbzxzt')">
            <el-select v-model="filters.connectStatus" :placeholder="$t('message.qxz') + $t('message.sbzxzt')" clearable>
              <el-option
                :label="$t('message.qb')"
                value=""
              />
              <el-option
                v-for="item in connectStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-preventReClick type="primary" @click="getList(1)">{{ $t('message.cz') }}</el-button>
            <el-button v-preventReClick @click="clear">{{ $t('message.clear') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="active" @tab-click="handleClick">
        <el-tab-pane
          v-for="(model, index) in manufacturerList"
          :key="index"
          :label="model.manufacturer"
          :name="index.toString()"
        >
          <div class="doumee-filter manufacturer">
            <div>
              <el-button v-if="meta.indexOf('deviceCourseAdd') > -1" v-preventReClick type="primary" @click="addDevice">{{ $t('message.add') }}</el-button>
            </div>
            <div class="detail" @click="manufacturerDetail(model.id)"><i class="el-icon-warning-outline" /> {{ $t('message.cssm') }}</div>
          </div>
        </el-tab-pane>
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="55"
          />
          <el-table-column align="center" :label="$t('message.sbId')" prop="devCode" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.sbmc')" prop="name" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.sbwz')" prop="devAddr" min-width="140" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.sbxh')" prop="devItemNo" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.yhm')" prop="devUserName" min-width="120" show-overflow-tooltip />
          <!-- <el-table-column align="center" :label="$t('message.glmbmc')" prop="devTicketTemplateName" min-width="120" show-overflow-tooltip /> -->
          <el-table-column align="center" :label="$t('message.sbzt')" min-width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.state"
                :active-value="'1'"
                :inactive-value="'0'"
                :disabled="meta.indexOf('deviceCourseStatus') === -1"
                @change="toConfigUpdate(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('message.sbzxzt')" prop="connectStatus" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <span
                v-if="scope.row.connectStatus === '0'"
                class="secondColor"
              >{{ $t('message.lixian') }}</span>
              <span v-else>{{ $t('message.zaixian') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="creator" :label="$t('message.cjr')">
          </el-table-column>
          <el-table-column :label="$t('message.caozuo')" align="center" min-width="140" fixed="right">
            <template slot-scope="scope">
              <div class="flex-cc">
                <el-button v-if="meta.indexOf('deviceCourseEdit') > -1" v-preventReClick type="text" @click="toEdit(scope.row,1)">{{ $t('message.edit') }}</el-button>
                <!-- <el-button v-if="meta.indexOf('deviceCourseDetail') > -1" v-preventReClick type="text" @click="toEdit(scope.row,2)">{{ $t('message.xianqing') }}</el-button> -->
                <el-button v-if="meta.indexOf('deviceCourseDelete') > -1" v-preventReClick class="secondColor" type="text" @click="toDel(scope.row.id)">{{ $t('message.del') }}</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tabs>
      <Paginations
        :total="totalCount"
        :page="pagination.page"
        @current-change="getList"
        @SizeChange="handleSizeChange"
      />
    </div>
    <el-dialog v-if="dialogTableVisible" :title="title" :visible.sync="dialogTableVisible" width="600px" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <el-form
        ref="newPrinter"
        class="doumee-form"
        :model="newPrinter"
        :rules="rules"
        label-suffix="："
        label-width="auto"
      >
        <el-form-item :label="$t('message.sbmc')" prop="name">
          <el-input
            v-model="newPrinter.name"
            :readonly="val==2"
            :placeholder="$t('message.qsr') + $t('message.sbmc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sbId')" prop="devCode">
          <el-input
            v-model="newPrinter.devCode"
            :readonly="val==2"
            :placeholder="$t('message.qsr') + $t('message.sbId')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.yhm')" prop="devUserName">
          <el-input
            v-model="newPrinter.devUserName"
            :readonly="val==2"
            :placeholder="$t('message.qsr') + $t('message.yhm')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sbmm')" prop="devUserPwd">
          <el-input
            v-model="newPrinter.devUserPwd"
            :readonly="val==2"
            :placeholder="$t('message.qsr') + $t('message.sbmm')"
          />
          <!-- type="password" -->
        </el-form-item>
        <el-form-item :label="$t('message.sbxh')" prop="devItemNo">
          <el-input
            v-model="newPrinter.devItemNo"
            :readonly="val==2"
            :placeholder="$t('message.qsr') + $t('message.sbxh')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sbwz')" prop="devAddr">
          <el-input
            v-model="newPrinter.devAddr"
            :readonly="val==2"
            :placeholder="$t('message.qsr') + $t('message.sbwz')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{ $t('message.qx') }}</el-button>
        <el-button v-if="val == 1" v-preventReClick :loading="subLoading" type="primary" @click="save">{{ $t('message.baocun') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { manufacturerList, manufacturerDetail, devCourseList, devCourseEdit, devCourseChangeState, devCourseAdd, devCourseGetDetail, devCourseDelete } from '@/api'
import { parseTime } from '@/utils'
import store from '@/store'
export default {
  name: 'DeviceCourse',
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      active: '0',
      swiperOptions: {
        slidesPerView: 'auto',
        pagination: {
          el: '.swiper-pagination'
        }
      },
      pagination: {
        page: 1,
        rows: 10
      },
      dialogTableVisible: false,
      totalCount: 10,
      list: [],
      listLoading: true,
      stateList: [
        { value: '1', label: this.$t('message.qy') },
        { value: '0', label: this.$t('message.jy') }
      ],
      connectStatusList: [
        { value: '0', label: this.$t('message.lixian') },
        { value: '1', label: this.$t('message.zaixian') }
      ],
      deviceStatus: [
        { value: '1', label: this.$t('message.qy') },
        { value: '0', label: this.$t('message.jy') }
      ],
      areaList: [],
      manufacturerList: [],
      filters: {},
      newPrinter: {},
      selList: [],
      dialogGlmb: false,
      meta: [],
      mbForm: {},
      mbList: [],
      val: 1,
      title: '',
      rules: {
        name: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.sbmc'), trigger: 'blur' }
        ],
        devTicketTemplateId: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.moban'), trigger: 'change' }
        ],
        devCode: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.sbId'), trigger: 'blur' }
        ],
        devUserName: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.yhm'), trigger: 'blur' }
        ],
        devUserPwd: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.sbmm'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.listLoading = false
    this.meta = this.$route.meta.buttons || []
    this.initData()
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    // 删除
    toDel(id) {
      this.$confirm(this.$t('message.isdel'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          devCourseDelete({ param: { id }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            this.getList(1)
          })
            .catch(() => { })
        }
      }).finally(() => {})
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleSelectionChange(val) {
      this.selList = val
    },
    handleClick() {
      this.getList(1)
    },
    // 列表修改状态
    toConfigUpdate(row) {
      console.log(row)
      this.listLoading = true
      devCourseChangeState({ param: { id: row.id, state: row.state }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          console.log(res, '客消状态')

          this.$message.success(this.$t('message.xgcg'))
        }
        this.getList()
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 新增按钮
    addDevice() {
      this.newPrinter = {
        manufacturerId: this.manufacturerList[this.active].id
      }
      this.title = this.$t('message.add')
      this.dialogTableVisible = true
    },
    // 详情
    toEdit(item, val) {
      devCourseGetDetail({ param: { id: item.id }}).then(res => {
        if (res.errorCode === '000000') {
          this.newPrinter = {
            ...res.record,
            manufacturerId: this.manufacturerList[this.active].id
          }
          this.title = val === 1 ? this.$t('message.edit') : this.$t('message.xianqing')
          this.dialogTableVisible = true
          this.val = val
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取tabs
    initData() {
      manufacturerList({ param: { type: 10 }}).then(res => {
        if (res.errorCode === '000000') {
          console.log(res, 'manufacturerList')

          this.manufacturerList = res.recordList
          this.getList(1)
        }
      }).catch(err => {
        console.log(err)
      })
      // manufacturerDetail()
    },
    // 列表
    getList(page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      devCourseList({ pagination, param: { venueId, manufacturerId: this.manufacturerList[this.active].id, ...filters }}).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.totalCount = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    clear() {
      this.filters = {}
      this.getList()
    },
    cancel() {
      this.dialogTableVisible = false
    },
    // 确认按钮 修改编辑
    save() {
      this.$refs.newPrinter.validate((valid) => {
        if (valid) {
          this.subLoading = true
          const param = { ...this.newPrinter }
          if (param.id) {
            devCourseEdit({ param }).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.editcg'))
                this.getList()
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          } else {
            devCourseAdd({ param:{...param,state:'1'} }).then(res => {
              // console.log(res)
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.addcg'))
                this.getList()
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          }
        } else {
          // this.$alert(this.$t('message.qxwssbxx'), this.$t('message.cw'))
        }
      })
    },
    // 厂商说明
    manufacturerDetail() {
      manufacturerDetail({ param: { manufacturerId: this.manufacturerList[this.active].id }}, sessionStorage.getItem('venueId')).then(res => {
        // console.log(res)
        if (res.errorCode === '000000') {
          const cont = res.record.manufacturer + res.record.text.replace(/\n/g, '<br/>')
          this.$alert(cont, this.$t('message.cssm'), {
            dangerouslyUseHTMLString: true
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
</style>
